package com.dkm.ec.sale.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.dkm.base.core.util.string.StringUtils;
import com.dkm.biz.gl.domain.EavAttribute;
import com.dkm.biz.gl.persistence.entity.EavAttributePo;
import com.dkm.biz.gl.persistence.entity.EavSetAttrPo;
import com.dkm.biz.gl.persistence.entity.GlConfigPo;
import com.dkm.biz.gl.repository.EavAttributeRepository;
import com.dkm.biz.gl.repository.EavSetAttrRepository;
import com.dkm.biz.gl.repository.GlConfigRepository;
import com.dkm.biz.gl.service.EavAttrService;
import com.dkm.ec.product.persistence.entity.ProductMediaPo;
import com.dkm.ec.product.repository.ProductMediaRepository;
import com.dkm.ec.sale.domain.SaleEntity;
import com.dkm.ec.sale.domain.SaleSku;
import com.dkm.ec.sale.persistence.entity.SaleEntityPo;
import com.dkm.ec.sale.persistence.entity.SaleEntityStatPo;
import com.dkm.ec.sale.persistence.entity.SalePricePo;
import com.dkm.ec.sale.persistence.entity.SaleSkuPo;
import com.dkm.ec.sale.persistence.entity.SaleSkuTagPo;
import com.dkm.ec.sale.repository.SaleEntityRepository;
import com.dkm.ec.sale.repository.SaleEntityStatRepository;
import com.dkm.ec.sale.repository.SalePriceRepository;
import com.dkm.ec.sale.repository.SaleSkuRepository;
import com.dkm.ec.sale.repository.SaleSkuTagRepository;
import com.dkm.ec.sale.service.SaleEntityService;
import com.dkm.ec.sale.service.SaleSkuService;
@Service
public class SaleEntityServiceImpl implements SaleEntityService{
	
	private static Logger logger = LoggerFactory.getLogger(SaleEntityServiceImpl.class);
	@Resource
	private SaleSkuRepository saleSkuRepository;
	@Resource
	private SaleEntityRepository saleEntityRepository;
	@Resource
	private SalePriceRepository salePriceRepository;
	@Resource
	private SaleEntityStatRepository saleEntityStatRepository;
	@Resource
	private EavSetAttrRepository eavSetAttrRepository;
	@Resource
	private EavAttributeRepository eavAttributeRepository;
	@Resource
	private ProductMediaRepository productMediaRepository;
	@Resource
	private GlConfigRepository glConfigRepository;
	@Resource
	private SaleSkuService saleSkuService;
	
	@Resource
	private SaleSkuTagRepository saleSkuTagRepository;
	//@Resource
//	private StockRepository stockRepository;
	
	@Resource
	private EavAttrService eavAttrService;
	/**
	 * 获取id_为id的产品详情
	 * @Param key product的key
	 * @return SaleEntityPo
	 */
	public SaleEntityPo getDetailByKeyType(String key, String callType){
		//获取产品
					
				SaleEntityPo saleEntityPo =  saleEntityRepository.getByKey(key);
				//获取saleEntity普通属性
				if(StringUtils.isNotEmpty(saleEntityPo.getEavSetKey())){
					saleEntityPo.setEavSetGroupPos(eavAttrService.getAttrNoSkuByProdSetKey(saleEntityPo.getSaleId(), saleEntityPo.getEavSetKey()));	
				}
				/*//获取media
				//获取SKU的首图 获取图片大小 
				if(StringUtils.isNotEmpty(saleEntity.getData().getEavSetKey())){
					//获取sku主sku属性对应的optionid
					EavSetAttrPo eavSetAttrPo = eavSetAttrRepository.getMainSkuAttrBySetKey(saleEntity.getData().getEavSetKey());
					String[] attrList = saleSkuPo.getAttrIds().split(",");
					String attrOpId = "";
					for(int i=0;i<attrList.length;i++){
						if(eavSetAttrPo.getAttrId().equals(attrList[i])){
							String[] attrOps = saleSkuPo.getAttrOpIds().split(",");
							attrOpId = attrOps[i];
							break;
						}
					}
					if(StringUtils.isNotEmpty(attrOpId)){
						ProductMediaPo productMediaPo = productMediaRepository.getMainMediaPoByProdIdAttrOpId(saleEntity.getData().getId(),attrOpId);//
						saleSkuPo.setMainCloudPath(productMediaPo.getCloudPath());	
					}
					
				}else{
					ProductMediaPo productMediaPo = productMediaRepository.getMainMediaPoByProdId(saleEntity.getData().getId());
					if(productMediaPo!=null) saleSkuPo.setMainCloudPath(productMediaPo.getCloudPath());
				}*/
				//获取glconfig中设置的图片缩放比率
				/*GlConfigPo glConfigPo = glConfigRepository.getByConfigKey("mainProductMediaSize");
				saleSkuPo.setImgSizeMap(glConfigPo.getOptionsMap());*/
				//获取sku所在产品对应的所有sku
				List<SaleSkuPo> skuPos = saleSkuRepository.findByProdId(saleEntityPo.getId());
				for(SaleSkuPo saleSkuPo:skuPos){
					//获取sku对应的所有价格
					List<SalePricePo> salePricePos = salePriceRepository.findBySkuId(saleSkuPo.getId());
					saleSkuPo.setSalePricePos(salePricePos);
					//获取sku对应的产品统计
					SaleEntityStatPo saleEntityStatPo = saleEntityStatRepository.getBySkuId(saleSkuPo.getId());
					saleSkuPo.setSaleEntityStatPo(saleEntityStatPo);
				}
				saleEntityPo.setSaleSkuPos(skuPos);
				
				
				
		
		return saleEntityPo;
	}
	@Override
	public SaleEntityPo getDetailBySkuType(String skuId, String callType,boolean isSingle) {
		SaleSku saleSku = saleSkuRepository.load(skuId);
		SaleEntityPo saleEntityPo = new SaleEntityPo();
		/*if(saleSku!=null){
			SaleEntity saleEntity =  saleEntityRepository.load(saleSku.getData().getSaleProdId());
			saleEntityPo = saleEntity.getData();
			if(saleEntityPo!=null){
				//获取saleEntity普通属性
				if(StringUtils.isNotEmpty(saleEntityPo.getEavSetKey())){
					saleEntityPo.setEavSetGroupPos(eavAttrService.getAttrNoSkuByProdSetKey(saleEntityPo.getSaleId(), saleEntityPo.getEavSetKey()));	
				}
				
				//获取sku所在产品对应的所有sku
//				List<SaleSkuPo> skuPos = saleSkuRepository.findByProdId(saleEntityPo.getId());
				Map<String, Object> paramsMap = new HashMap<String,Object>();
				paramsMap.put("whereSql", " s.sale_prod_id_ = '"+saleEntityPo.getId()+"' and s.status_ != 'delete'");
				List<SaleSkuPo> skuPos = saleSkuRepository.findByProdId2(paramsMap);
				
				
				GlConfigPo glConfigPo = glConfigRepository.getByConfigKey("mainProductMediaSize");
				//库存处理
				Stock stock = stockRepository.newInstance();
				List<SaleSkuPo> newSaleSkuPos = new ArrayList<SaleSkuPo>();
				for(SaleSkuPo saleSkuPo:skuPos){
					//判断是否返回单个sku信息或者多个
					if(isSingle){
						if(!skuId.equals(saleSkuPo.getId())){
							continue;
						}
					}
					if(!(saleSkuPo.getStatus().equals("not_on_sell") || saleSkuPo.getStatus().equals("delete"))){
						
						//进行两次的库存处理，因为返回的JSON嵌套数据在不同标签下。
						//处理库存
						try{
							Integer qtyStock = stock.queryStock(saleSkuPo.getId(), callType);
							saleSkuPo.setMaxTotal(qtyStock);
							if(qtyStock <= 0) saleSkuPo.setStatus("sold_out");
							if(1 <= qtyStock && qtyStock <= StockStatus.STOCK_INTEGER){
								saleSkuPo.setStockStatus(StockStatus.STOCK_STRING);
							}
						}catch(Exception ex){
							logger.info("获取库存出错：skuId: " + skuId +", callType:" + callType, ex);
						}
					}
					
					//获取sku对应的所有价格
					List<SalePricePo> salePricePos = salePriceRepository.findBySkuId(saleSkuPo.getId());
					List<SalePricePo> newSalePricePos = new ArrayList<SalePricePo>(); 
					for(SalePricePo salePricePo : salePricePos){
						if(salePricePo.getStatus().equals("on_sale")){
							newSalePricePos.add(salePricePo);
						}else {
							continue;	
						}
						//处理库存
						try{
							Integer qtyStock = stock.queryStock(salePricePo.getProdSkuId(), callType);
							salePricePo.setMaxTotal(qtyStock);
							if(qtyStock <= 0) salePricePo.setStatus("sold_out");
						}catch(Exception ex){
							logger.info("获取库存出错：skuId: " + skuId +", callType:" + callType, ex);
						}
					}
					saleSkuPo.setSalePricePos(newSalePricePos);
					//获取sku对应的产品统计
					SaleEntityStatPo saleEntityStatPo = saleEntityStatRepository.getBySkuId(saleSkuPo.getId());
					saleSkuPo.setSaleEntityStatPo(saleEntityStatPo);
					saleSkuPo.setImgSizeMap(glConfigPo.getOptionsMap(callType));
					
					Map<String,Object> eavAttrMap = new HashMap<String, Object>();
					//获取sku对应的主图
					//获取SKU的首图 
					if(StringUtils.isNotEmpty(saleEntity.getData().getEavSetKey())){
						
						//获取sku主sku属性对应的optionid
						EavSetAttrPo eavSetAttrPo = eavSetAttrRepository.getMainSkuAttrBySetKey(saleEntity.getData().getEavSetKey());//主SKU属性
						
						String[] attrList = {};
						String  attrIdsStr= saleSkuPo.getAttrIds();
						if(attrIdsStr!=null){
							attrList = attrIdsStr.split(",");
						}						
						//String[] attrList = saleSkuPo.getAttrIds().split(",");
						String attrOpId = "";
						for(int i=0;i<attrList.length;i++){
							if(eavSetAttrPo!=null&&eavSetAttrPo.getAttrId()!=null&&eavSetAttrPo.getAttrId().equals(attrList[i])){
								String[] attrOps = saleSkuPo.getAttrOpIds().split(",");
								attrOpId = attrOps[i];
								break;
							}
						}
						if(!saleSkuPo.getStatus().equals("delete")){
							if(saleEntityPo.getAttrDataMap()==null){
								for(int i=0;i<attrList.length;i++){
										EavAttribute eavAttribute = eavAttributeRepository.load(attrList[i]);
										if(eavAttribute!=null) {
											EavAttributePo eavAttributePo = eavAttribute.getData();
											eavAttrMap.put(eavAttributePo.getId(), eavAttributePo.getCtrlType());
										}
								}
								saleEntityPo.setAttrDataMap(eavAttrMap);
							}
						}
						
						if(StringUtils.isNotEmpty(attrOpId)){
							ProductMediaPo productMediaPo = productMediaRepository.getMainMediaPoByProdIdAttrOpId(saleEntityPo.getId(),attrOpId);//
							saleSkuPo.setProductMediaPo(productMediaPo);
							//获取每个SKU所有的橱窗图
							List<ProductMediaPo> productMediaPos = productMediaRepository.findByProdIdForSale(saleEntityPo.getId(),"Y","image",attrOpId);
							saleSkuPo.setProductMediaPoList(productMediaPos);
						}else{
							ProductMediaPo productMediaPo = productMediaRepository.getMainMediaPoByProdId(saleEntityPo.getId());
							if(productMediaPo!=null) saleSkuPo.setProductMediaPo(productMediaPo);
							//获取每个SKU所有的橱窗图
							List<ProductMediaPo> productMediaPos = productMediaRepository.findByProdIdForSale(saleEntityPo.getId(),"Y","image",null);
							saleSkuPo.setProductMediaPoList(productMediaPos);
						}
						
					}else{
						ProductMediaPo productMediaPo = productMediaRepository.getMainMediaPoByProdId(saleEntityPo.getId());
						if(productMediaPo!=null) saleSkuPo.setProductMediaPo(productMediaPo);
						//获取每个SKU所有的橱窗图
						List<ProductMediaPo> productMediaPos = productMediaRepository.findByProdIdForSale(saleEntityPo.getId(),"Y","image",null);
						saleSkuPo.setProductMediaPoList(productMediaPos);
					}
					
					String skuSpec = getSkuSpec(saleSkuPo.getId());
					saleSkuPo.setSkuSpec(skuSpec);
					
					//获取sku所有的标签
					//获取SKU的标签信息
					List<SaleSkuTagPo> saleSkuTagPos = saleSkuTagRepository.findBySkuId(saleSkuPo.getId());
					saleSkuPo.setSaleSkuTagPos(saleSkuTagPos);
					newSaleSkuPos.add(saleSkuPo);
					
				}
				saleEntityPo.setSaleSkuPos(newSaleSkuPos);
			}
			
		}*/
		
		return saleEntityPo;
	}
	
	public String getSkuSpec(String skuId){
		String spec = "";
		
		SaleSkuPo saleSkuPo = saleSkuService.getSaleSkuPoById(skuId);
		if(saleSkuPo!=null){
			String attrNames=saleSkuPo.getAttrNames();
			
			String attrOplabels=saleSkuPo.getAttrOpLabels();
		//	spec = AttrNameOpUtil.getSkuSpec(attrNames, attrOplabels);
		}
		return spec;
	}
	
	@Override
	public String getDefaultSkuId(String prodId) {
		SaleSkuPo saleSkuPo =saleSkuRepository.getDefaultSkuId(prodId);
		if(saleSkuPo!=null)		return saleSkuPo.getId();
		else return "";
	}
}
